package com.zxk.service.impl;

import com.sun.jna.platform.win32.WinDef;
import com.zxk.constant.JNAConstants;
import com.zxk.constant.PicConstants;
import com.zxk.entity.FindPicResult;
import com.zxk.service.Login;
import com.zxk.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 登录游戏
 *
 * @author: 舟小亢
 * @date: 2023-08-05 21:41
 */

public class LoginGameImpl implements Login {

    private static Logger LOG = LoggerFactory.getLogger(LoginGameImpl.class);

    /**
     * 截图时用句柄
     */
    private WinDef.HWND hwnd_0 = null;

    /**
     * 执行键鼠命令时用句柄
     */
    private WinDef.HWND hwnd_1 = null;

    /**
     * 备用句柄
     */
    private WinDef.HWND hwnd_2 = null;


    public LoginGameImpl(WinDef.HWND hwnd_0, WinDef.HWND hwnd_1, WinDef.HWND hwnd_2) {
        this.hwnd_0 = hwnd_0;
        this.hwnd_1 = hwnd_1;
        this.hwnd_2 = hwnd_2;
    }

    @Override
    public boolean execute() throws Exception {
        // 点击游戏图标
        if (!FuzzyPicUtil.findAndClickRandom(hwnd_0, hwnd_1, PicConstants.开始_梦幻西游图标,0.6)) {
            return false;
        }

        // 点击选服
        for (int i = 0; i < 60; i++) {
            if (PixelPicUtil.findPic(hwnd_0, PicConstants.开始_服务器红点, 2).isFinded()) {
                break;
            }
            // 点击屏幕，加快进度
            MouseUtil.lClickRandom(hwnd_1, 500, 300);
        }
        if (!PixelPicUtil.findAndClickRandom(hwnd_0, hwnd_1, PicConstants.开始_服务器红点, 2)) {
            return false;
        }

        // 点击已有角色
        if (!FuzzyPicUtil.findAndClickRandom(hwnd_0, hwnd_1, PicConstants.开始_已有角色)) {
            return false;
        }

        // 点击第一个角色
        if (!PixelPicUtil.findAndClickRandom(hwnd_0, hwnd_1, PicConstants.开始_第一个角色)) {
            return false;
        }

        // 不断通过ESC恢复初始状态
        for (int i = 0; i < 5; i++) {
            // 找点击空白界面
            FuzzyPicUtil.findAndClickRandom(hwnd_0, hwnd_1, PicConstants.公共_点击空白关闭, 3);

            // 找活动
            FindPicResult pic = PixelPicUtil.findPic(hwnd_0, PicConstants.公共_活动, 3);
            if (pic.isFinded()) {
                LOG.info("【登录游戏】成功");
                return true;
            }

            // 循环摁ESC，直到找到地图
            KeyUtil.kClick(hwnd_1, JNAConstants.VK_ESCAPE);
        }
        // 如果没找到，则退出
        LOG.error("【登录游戏】失败");

        return false;
    }

}
